package de.jowadroid.timekeeping;

import java.util.concurrent.TimeUnit;

import de.jowadroid.timekeeping.R;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
import android.widget.Toast;

public class TimekeeperWidgetProvider extends AppWidgetProvider {
	
	/**
	 * Custom Intent name that is used by the 'AlarmManager' to tell us to
	 * update the clock once per second.
	 */
	public static final String CLOCK_WIDGET_UPDATE = "de.jowadroid.timekeeping.TIMEKEEPING_WIDGET_UPDATE";
	public static final String START_BUTTON_UPDATE = "de.jowadroid.timekeeping.WIDGET_START_UPDATE";
	public static final String STOP_BUTTON_UPDATE  = "de.jowadroid.timekeeping.WIDGET_STOP_UPDATE";
	
	private static Boolean mTimeRuns = false;
	
	private static long mStartTime = 0;
	private static long mTimePause = 0;

	
	//onReceive gets the ACTION from broadcast and react depending to the action
	@Override
	public void onReceive(Context context, Intent intent) {
		
		super.onReceive(context, intent);

        //CLOCK_UPDATE every second to display time
		if (CLOCK_WIDGET_UPDATE.equals(intent.getAction())) {
//			Toast toast = Toast.makeText(context, "CLOCK_WIDGET_UPDATE", Toast.LENGTH_SHORT);
//			toast.show();


			// Get the widget manager and ids for this widget provider, then
			// call the shared clock update method.
			ComponentName thisAppWidget = new ComponentName(
					context.getPackageName(), getClass().getName());

			AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);

			int ids[] = appWidgetManager.getAppWidgetIds(thisAppWidget);

			for (int appWidgetID : ids) {
				updateWidgetClock(context, appWidgetManager, appWidgetID);
			}
		}

		if (START_BUTTON_UPDATE.equals(intent.getAction())) {
			if(mTimeRuns == false)
			{
				mTimeRuns = true;
			}
			RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget1);
			views.setTextViewText(R.id.start, "WEITER");

			Toast toast = Toast.makeText(context, "START_BUTTON_UPDATE", Toast.LENGTH_SHORT);
			toast.show();
		}

		if (STOP_BUTTON_UPDATE.equals(intent.getAction())) {
			if(mTimeRuns == true)
			{
				mTimeRuns = false;
			}
			
			RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget1);
			views.setTextViewText(R.id.stop, "FEIERABEND");

			Toast toast = Toast.makeText(context, "STOP_BUTTON_UPDATE", Toast.LENGTH_SHORT);
			toast.show();
		}
	}

	
	

	
	


	
	
	public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) 
	{
		final int N = appWidgetIds.length;

		// loop over each App Widget that belongs to this provider
		for (int i = 0; i < N; i++) {
			int appWidgetId = appWidgetIds[i];

			// Get the layout for the App Widget
			RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget1);
			
			PendingIntent pendingIntentStart = PendingIntent.getBroadcast(context, 0, new Intent(START_BUTTON_UPDATE), PendingIntent.FLAG_UPDATE_CURRENT);
			PendingIntent pendingIntentStop = PendingIntent.getBroadcast(context, 0, new Intent(STOP_BUTTON_UPDATE), PendingIntent.FLAG_UPDATE_CURRENT);
			
			views.setOnClickPendingIntent(R.id.start, pendingIntentStart);
			views.setOnClickPendingIntent(R.id.stop,  pendingIntentStop);

			// Tell the AppWidgetManager to perform an update on the current app widget
			appWidgetManager.updateAppWidget(appWidgetId, views);

			// Update the clock label using a shared method
			updateWidgetClock(context, appWidgetManager, appWidgetId);
		}
	}
	
	

	
	//static method to update a widget with new time (called every second)
	public static void updateWidgetClock(Context context, AppWidgetManager appWidgetManager, int appWidgetId) {

//		Date currentTimeD = new Date();
		RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.widget1);

//		updateViews.setTextViewText(R.id.tagesArbeitszeit, currentTime);
		
//		updateViews.setTextViewText(R.id.stop, "feierabend");

		if(mTimeRuns)
		{
			long currentTime = System.currentTimeMillis();
			if(mStartTime == 0)
			{
				mStartTime = currentTime;
			}
			long timeElapsed = currentTime - mStartTime - mTimePause;
			updateViews.setTextViewText(R.id.wochenArbeitszeit, String.format("%02d:%02d:%02d", 
					TimeUnit.MILLISECONDS.toHours(timeElapsed), 
					TimeUnit.MILLISECONDS.toMinutes(timeElapsed) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeElapsed)),
					TimeUnit.MILLISECONDS.toSeconds(timeElapsed) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(timeElapsed)) - TimeUnit.HOURS.toSeconds(TimeUnit.MILLISECONDS.toHours(timeElapsed)))
			);
		}
		
		if( (mTimeRuns == false) && (mStartTime != 0))
		{
			mTimePause += 1000;
		}

		appWidgetManager.updateAppWidget(appWidgetId, updateViews);
	}
	

	// creates update event which will be broadcasted by AlarmManager every 1sec
	private PendingIntent createClockTickIntent(Context context) {
		return  PendingIntent.getBroadcast(context, 0, new Intent(CLOCK_WIDGET_UPDATE), PendingIntent.FLAG_UPDATE_CURRENT);
	}

	// Called once the first instance of your widget is added
	@Override
	public void onEnabled(Context context) {
		super.onEnabled(context);


		RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget1);
		views.setTextViewText(R.id.start, "START");
		views.setTextViewText(R.id.stop, "STOP");

		// get alarmManager service for frequent updating events
		AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);

		//set alarm to call createClockTickIntent every 1 second
		alarmManager.setRepeating(AlarmManager.RTC, System.currentTimeMillis(), 1000, createClockTickIntent(context));
	}

	// Called once, the last instance of your widget is removed
	@Override
	public void onDisabled(Context context) {
		super.onDisabled(context);

		//get and disable the alarmManager service
		AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
		alarmManager.cancel(createClockTickIntent(context));
	}
}
